package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.printing.PrintJob;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	
	public class FahuoPrinter extends Sprite
	{
		private var tfcopy:TextField = new TextField;
		private var tfBtn:TextField = new TextField;
		
		public function FahuoPrinter()
		{
			tfcopy.height = 100;
			tfcopy.width = 200;
			tfcopy.type = TextFieldType.INPUT;
			tfcopy.multiline = true;
			tfcopy.border = true;
			addChild(tfcopy);
			
			tfBtn.text = "打印";
			tfBtn.border = true;
			tfBtn.autoSize = TextFieldAutoSize.CENTER;
			tfBtn.selectable = false;
			tfBtn.y = 110;
			tfBtn.x = 90;
			addChild(tfBtn);
			tfBtn.addEventListener(MouseEvent.CLICK, onPrint);
		}
		
		private function onPrint(e:Event):void{
			var data:Object = new Object();
			// 按行分割
			var arr:Array = tfcopy.text.split('\r');
			for each(var s:String in arr){
				if(s=="") continue;
				var cols:Array = s.split('\t');
				
				var client:Object = null;
				
				if(data[cols[4]+cols[12]] == null){
					data[cols[4]+cols[12]] = new Object();
					client = data[cols[4]+cols[12]];
					client['name'] = cols[4];
					// 年月日
					client['date'] = [cols[1],cols[2],cols[3]];
					// 责任人
					client['zerenren'] = cols[12];
					// 数据
					client['data'] = new Array();
				}
				
				client = data[cols[4]+cols[12]];
				
				// 填入数据
				(client['data'] as Array).push([
					cols[5], '', cols[6], cols[7],
					cols[8],cols[9], cols[10], cols[11]
				]);
			}
			
			// 打印队列
			var printQueue:Array = [];
			
			for each(var o:Object in data){
				var od:Array = (o['data'] as Array);
				for(var i:int = 0; i<od.length; ++i){
					var d:Array = [od[i]];
					if(i+1<od.length){
						d.push(od[++i]);
					}
					if(i+1<od.length){
						d.push(od[++i]);
					}
					var f:Fahuo = new Fahuo(
						o['name'], o['date'], o['zerenren'], d
					);
					
					printQueue.push(f);
				}
			}
			
			if(printQueue.length>0){
				var pj:PrintJob = new PrintJob(); 
				var rect:Rectangle = new Rectangle();
				rect.left = 0;
				rect.top = 0;
				rect.right = 595;
				rect.bottom = 420;
				
				if(pj.start()){
					for each(var p:Fahuo in printQueue){
						pj.addPage(p, rect);
					}
				}
				pj.send();
			}
		}
	}
}